﻿using Infrastructure.Web;
using MyData.Data.Repository;
using MyData.Dto;
using MyData.Models;
using MyDomain;
using MyRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace MyRepository
{
    public class AdminUserRepository : RepositoryBase<AdminUser>,IAdminUserRepository
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public AdminUser Login(string userName, string passWord)
        {
            using (var db = this.NewDB())
            {
                var entity = db.Query<AdminUser>().FirstOrDefault(c=>c.UserName==userName&&c.PassWord==passWord);
                if (entity == null) return null;
                return entity;
            }
        }
        public PageDto<AdminUserDto> GetAdminUser(QueryListModel query, string userName, string nickName)
        {
            using (var db = this.NewDB())
            {
                var adminUsers = db.Query<AdminUser>();
                if (!String.IsNullOrEmpty(userName))
                {
                    adminUsers = adminUsers.Where(c => c.UserName.Contains(userName));
                }
                if (!String.IsNullOrEmpty(nickName))
                {
                    adminUsers = adminUsers.Where(c => c.NickName.Contains(nickName));
                }
                var departs = db.Query<Depart>();
                List<AdminUserDto> dtos = new List<AdminUserDto>();
                foreach (var a in adminUsers.ToList())
                {
                    AdminUserDto dto = new AdminUserDto();
                    dto.Id = a.Id;
                    dto.LastLoginTime = a.LastLoginTime;
                    dto.Menus = a.Menus;
                    dto.NickName = a.NickName;
                    dto.PassWord = a.PassWord;
                    dto.UserName = a.UserName;
                    dto.CreatedTime = a.CreatedTime;
                    dto.DepartName= departs.FirstOrDefault(c => c.Id == a.DepartId)?.Name;
                    dtos.Add(dto);
                }
                var result = dtos.AsQueryable().Paging(query.Limit, query.Offset);
                return new PageDto<AdminUserDto>()
                {
                    total = result.total,
                    rows = result.rows
                };
            }
        }
    }
}
